package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.exception.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.product.util.UploadUtil;
import io.swagger.annotations.Api;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Description: TODO
 * @Author: Mr.Cao
 * @DateTime: 2021/9/29 20:44
 * BMW F750GS
 **/
@Api(tags = "上传管理接口")//swagger注解
@RestController
@RequestMapping("admin/product")
@RefreshScope //扩展配置文件内容变更, 不需要重启服务器
public class FileUploadController {

    @Value("${img.url}")
    private String imgUrl;

    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file){
        try {
            //获取文件的扩展名
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            //调用文件上传工具类, 上传文件
            String url = UploadUtil.fileUpload(file.getBytes(), extension);
            return Result.ok(imgUrl+url);
        } catch (IOException e) {
            e.printStackTrace();
            //抛出自定义异常
            throw new GmallException("文件上传失败", ResultCodeEnum.FAIL.getCode());
        }

    }
}
